#include "myserialport.h"

MySerialPortSettings::MySerialPortSettings()
{
}

MySerialPortSettings::MySerialPortSettings(const MySerialPortSettings& setting)
{
    portName=setting.portName;
    baudRate=setting.baudRate;
    parity=setting.parity;
    dataBits=setting.dataBits;
    stopBits=setting.stopBits;
    flowControl=setting.flowControl;

}

MySerialPortSettings & MySerialPortSettings::operator=(const MySerialPortSettings &setting)
{
    if(this!=&setting)
    {
        portName=setting.portName;
        baudRate=setting.baudRate;
        parity=setting.parity;
        dataBits=setting.dataBits;
        stopBits=setting.stopBits;
        flowControl=setting.flowControl;
    }
    return *this;
}


MySerialPort::MySerialPort(const MySerialPortSettings & setting,RES& res,QObject *parent):
    QObject(parent)
  ,_thread(nullptr)
  ,_sp(nullptr)
{
    _sp=new QSerialPort();
    int returnCode=init(setting);

    if(returnCode<0)
    {
        res.returnCode=returnCode;
        res.msg=_sp->errorString();
        return;
    }

    //_receTimer.moveToThread(_thread);

    //connect(&_receTimer,&QTimer::timeout,this,&MySerialPort::slReceiveTimeOut);

}

MySerialPort::~MySerialPort()
{

    if(_thread)
    {
        _thread->quit();
        _thread->wait();
        _thread->deleteLater();
    }
    if(_sp)
    {
        _sp->deleteLater();
    }
    qDebug()<<"MySerialPort Destroyed!";
}

int MySerialPort::init(const MySerialPortSettings & setting)
{
    _sp->setPortName(setting.portName);
    _sp->setBaudRate(setting.baudRate);
    _sp->setDataBits(setting.dataBits);
    _sp->setParity(setting.parity);
    _sp->setStopBits(setting.stopBits);
    _sp->setFlowControl(setting.flowControl);
    //_sp->setReadBufferSize(1024);
     if(_sp->open(QIODevice::ReadWrite))
     {
         qDebug() << "MySerialPort opened successfully!";
         _thread=new QThread();
         _sp->moveToThread(_thread);
         this->moveToThread(_thread);
         _thread->start();
         connect(_sp,&QSerialPort::readyRead,this,&MySerialPort::slReceiveData,Qt::QueuedConnection);
     }
     else
     {
         qDebug() << "Failed to open MySerialPort:"<<_sp->errorString();
         return -1;
     }


     return 0;
}


void MySerialPort::slReceiveData()
{
    //if(!_receTimer.isActive()) _receTimer.start(30);
    //QMutexLocker locker(&_mutex);
    //_receBytes.append(_sp->readAll());
    emit sgSPReceiveData(_sp->readAll());
   //     emit sgSPReceiveData(dk,_receiveDataMap[dk].data);
}


void MySerialPort::slSendData(QByteArray data)
{
    int res=_sp->write(data);
    qDebug() <<"send:"<<data;
    if(res<0)
    {
        qDebug() <<"bad write";
    }
}
